const fs = require('fs');
const path = require('path');
const events = require('events');
const puppeteer = require('puppeteer-extra');
const StealthPlugin = require('puppeteer-extra-plugin-stealth');
const AdmZip = require('adm-zip');
const config = require(path.join(process.cwd(), 'iconfontConfig.js'));

// 设置事件监听器限制
events.EventEmitter.defaultMaxListeners = 20;
process.setMaxListeners(20);

puppeteer.use(StealthPlugin());

async function downloadIconfont(debug = false) {
    let browser;
    try {
        // 创建最终保存目录
        const targetDir = path.join(process.cwd(), config.saveDir);

        if (!fs.existsSync(targetDir)) {
            fs.mkdirSync(targetDir, { recursive: true });
        }

        // 启动浏览器
        browser = await puppeteer.launch({
            headless: debug ? false : 'new',
            devtools: debug,
            slowMo: debug ? 50 : 0,
            args: ['--no-sandbox']
        });

        const page = await browser.newPage();

        // 设置下载行为
        const client = await page.target().createCDPSession();
        await client.send('Page.setDownloadBehavior', {
            behavior: 'allow',
            downloadPath: targetDir
        });

        // 登录 iconfont
        console.log('正在登录 iconfont...');
        await page.goto('https://www.iconfont.cn/login');

        // 记录登录前的 URL
        const beforeLoginUrl = await page.url();

        // 等待用户输入
        await page.waitForSelector('#userid');

        // 输入用户名和密码
        await page.type('#userid', config.username);
        await page.type('#password', config.password);

        // 点击登录按钮并等待响应
        try {
            // 点击登录按钮
            await page.click('.mx-btn-submit');
            
            // 等待登录完成 - 使用页面URL变化或特定元素出现来判断
            await Promise.race([
                page.waitForNavigation({ timeout: 5000 }),
                page.waitForSelector('.user-info', { timeout: 5000 }) // 假设登录后有用户信息元素
            ]);
            
            // 检查是否登录成功
            const currentUrl = await page.url();
            const userInfo = await page.$('.user-info');
            if (currentUrl.includes('login') || !userInfo) {
                throw new Error('登录失败：请检查用户名或密码');
            }
            
            console.log('登录成功！');

        } catch (error) {
            throw new Error('登录失败：' + error.message);
        }

        // 进入项目配置页面
        console.log(`正在进入项目: ${config.projectName}`);
        await page.goto('https://www.iconfont.cn/manage/index?manage_type=myprojects', {
            waitUntil: 'networkidle0'
        });

        // 等待项目列表加载
        await page.waitForSelector('.nav-container', { timeout: 10000 });

        // 获取下载前的文件列表
        const beforeFiles = fs.readdirSync(targetDir);

        // 在项目列表点击部分添加重试
        let found = false;
        let retries = 0;
        const maxRetries = 3;
        
        while (!found && retries < maxRetries) {
            found = await page.evaluate((projectName) => {
                const navItems = document.querySelectorAll('.nav-container .nav-item');
                for (const item of navItems) {
                    const span = item.querySelector('span');
                    if (span && span.textContent.trim() === projectName) {
                        item.click();
                        return true;
                    }
                }
                return false;
            }, config.projectName);
            
            if (!found) {
                console.log(`尝试 ${retries + 1}/${maxRetries}: 未找到项目"${config.projectName}", 重试中...`);
                await new Promise(resolve => setTimeout(resolve, 1000));
                retries++;
            }
        }
        
        if (!found) {
            throw new Error(`未找到项目分类: ${config.projectName}`);
        }

        // 等待项目列表更新
        await new Promise(resolve => setTimeout(resolve, 1000));

        // 等待按钮组加载完成
        await page.waitForSelector('.btn-group .btn-group-item', { timeout: 10000 });

        // 点击下载按钮
        await page.evaluate(() => {
            const downloadBtn = document.querySelector('.btn-group .btn-group-item');
            if (downloadBtn) {
                downloadBtn.click();
            }
        });

        // 等待新文件下载完成
        let zipFile = null;
        let attempts = 0;
        const maxAttempts = 10;
        const checkInterval = 1000; // 检查间隔1秒
        
        console.log('等待下载完成...');
        while (!zipFile && attempts < maxAttempts) {
            await new Promise(resolve => setTimeout(resolve, checkInterval));
            const afterFiles = fs.readdirSync(targetDir);
            const newFiles = afterFiles.filter(file => !beforeFiles.includes(file));
            zipFile = newFiles.find(file => file.endsWith('.zip'));
            attempts++;
            if (attempts % 3 === 0) {
                console.log(`已等待${attempts}秒...`);
            }
        }

        if (!zipFile) {
            throw new Error('下载失败：下载超时');
        }

        // 解压文件到目标目录
        const zipPath = path.join(targetDir, zipFile);
        const zip = new AdmZip(zipPath);
        const zipEntries = zip.getEntries();

        // 复制需要的文件到目标目录
        for (const entry of zipEntries) {
            const fileName = path.basename(entry.entryName);
            // 只复制需要的文件
            if (!config.exclude.includes(fileName)) {
                const content = entry.getData();
                fs.writeFileSync(path.join(targetDir, fileName), content);
                console.log(`已下载文件: ${fileName}`);
            }
        }

        // 删除下载的 zip 文件
        fs.unlinkSync(zipPath);

        // 删除以 font_ 开头的文件夹
        const files = await fs.readdirSync(targetDir);
        for (const file of files) {
            if (file.startsWith('font_')) {
                const filePath = path.join(targetDir, file);
                console.log(`准备删除文件夹: ${filePath}`);
                try {
                    fs.rmSync(filePath, { recursive: true, force: true });
                    console.log(`已删除文件夹: ${filePath}`);
                } catch (error) {
                    console.error(`删除文件夹失败: ${filePath}`, error.message);
                }
            }
        }

        console.log(`项目 ${config.projectName} 的文件已保存到 ${targetDir}`);

    } catch (error) {
        console.error('发生错误：', error.message);
        if (debug) {
            console.log('请手动检查浏览器状态，完成后关闭浏览器窗口');
            await new Promise(resolve => setTimeout(resolve, 3000));
        }
    } finally {
        if (browser) {
            try {
                await browser.close();
            } catch (error) {
                console.error('关闭浏览器时发生错误：', error.message);
            }
        }
        // 确保进程退出
        process.exit(0);
    }
}

// 如果直接运行此文件
if (require.main === module) {
    downloadIconfont(false); // 关闭调试模式
}

// 导出函数
module.exports = downloadIconfont;